//
//  EMAddressMgrViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 15/1/30.
//  Copyright (c) 2015年 cczu. All rights reserved.
//

#import "EMAddressMgrViewController.h"
#import "UINavigationController+EMNavi.h"
#import "EMAddAddressViewController.h"
#import "EMAddressInfo.h"
#import "MBProgressHUD.h"
#import "EMGetAddressReqBody.h"
#import "EMGetAddressRespBody.h"
#import "AppDelegate.h"
#import "EMSetAndDeleteAddressReqBody.h"
#import "EMSetAndDeleteAddressRespBody.h"
#import "UserInfo.h"
@interface EMAddressMgrViewController ()
{
    AppDelegate *app;
    UITableView *messageTable;
}
@end

@implementation EMAddressMgrViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.backgroundColor = RGB(242, 242, 242);
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.navigationItem.title = @"地址管理";
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 32);
    [button setImage:[UIImage imageNamed:@"button_导航_返回_白"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    
    UIButton *regButton =[UIButton buttonWithType:UIButtonTypeCustom];
    regButton.frame=CGRectMake(0, 0, 80, 32);
    regButton.titleLabel.font = [UIFont fontWithName:HEITILIGHT size:16];
    [regButton setTitle:@"添加新地址" forState:UIControlStateNormal];
    [regButton addTarget:self action:@selector(addAddressAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:regButton];
    
    [self getUserAddress];
    
}
- (void)backAction: (UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)addAddressAction:(UIButton *)sender
{
    EMAddAddressViewController *controller = [[EMAddAddressViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    messageTable = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    messageTable.delegate = self;
    messageTable.dataSource = self;
    messageTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:messageTable];
}

- (void)getUserAddress
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMGetAddressReqBody *reqBody = [[EMGetAddressReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"GET-USER-ADDRESS";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMGetAddressRespBody *respBody = [EMGetAddressRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            _addressArray = respBody.SUCCESSFULINFO;
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"addrCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    UIView *addrView = [[UIView alloc] init];
    addrView.frame = CGRectMake(W(5), H(5), W(310), H(90));
    addrView.backgroundColor = [UIColor whiteColor];
    addrView.layer.cornerRadius = 10;
    addrView.layer.borderWidth = 1;
    addrView.layer.borderColor = RGB(112, 179, 81).CGColor;
    
    EMAddressInfo *info = [[EMAddressInfo alloc] initWithAddressInfo:self.addressArray[indexPath.row]];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(10), H(10), W(250), H(20))];
    titleLabel.text = [info.m_isDefault isEqualToString:@"1"] ?  @"默认地址" : @"";
    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:16];
    [addrView addSubview:titleLabel];
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(20), H(35), W(100), H(20))];
    
    nameLabel.text = [NSString stringWithFormat:@"收件人:%@",info.m_name];
    nameLabel.textColor = [UIColor darkGrayColor];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
    [addrView addSubview:nameLabel];
    UILabel *phoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(170), H(35), W(130), H(20))];
    phoneLabel.numberOfLines = 2;
    phoneLabel.text = [NSString stringWithFormat:@"联系电话:%@",info.m_mobile];
    phoneLabel.textColor = [UIColor darkGrayColor];
    phoneLabel.textAlignment = NSTextAlignmentLeft;
    phoneLabel.textColor = [UIColor grayColor];
    phoneLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
    [addrView addSubview:phoneLabel];
    UILabel *addrLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(20), H(50), W(280), H(40))];
    addrLabel.numberOfLines = 2;
    addrLabel.text = [NSString stringWithFormat:@"收获地址：%@%@%@%@",info.m_province, info.m_city, info.m_area, info.m_detail];
    addrLabel.textColor = [UIColor darkGrayColor];
    addrLabel.textAlignment = NSTextAlignmentLeft;
    addrLabel.textColor = [UIColor grayColor];
    addrLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
    [addrView addSubview:addrLabel];
    
    UIButton *setDefaultAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    setDefaultAddressBtn.frame = CGRectMake(W(140), H(10), W(80), H(25));
    [setDefaultAddressBtn setTitle:@"设置默认地址" forState:UIControlStateNormal];
    [setDefaultAddressBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    setDefaultAddressBtn.titleLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
    setDefaultAddressBtn.layer.cornerRadius = 5;
    setDefaultAddressBtn.layer.borderWidth = 1;
    setDefaultAddressBtn.layer.borderColor = RGB(112, 179, 81).CGColor;
    setDefaultAddressBtn.tag = 1000 + indexPath.row;
    [setDefaultAddressBtn addTarget:self action:@selector(setDefaultAddress:) forControlEvents:UIControlEventTouchUpInside];
    [addrView addSubview:setDefaultAddressBtn];
    
    UIButton *deleteAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteAddressBtn.frame = CGRectMake(W(230), H(10), W(60), H(25));
    [deleteAddressBtn setTitle:@"删除地址" forState:UIControlStateNormal];
    [deleteAddressBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    deleteAddressBtn.titleLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
    deleteAddressBtn.layer.cornerRadius = 5;
    deleteAddressBtn.layer.borderWidth = 1;
    deleteAddressBtn.layer.borderColor = RGB(112, 179, 81).CGColor;
    deleteAddressBtn.tag = 1500 + indexPath.row;
    [deleteAddressBtn addTarget:self action:@selector(deleteAddress:) forControlEvents:UIControlEventTouchUpInside];
    [addrView addSubview:deleteAddressBtn];
    
    [cell addSubview:addrView];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return H(100);
}

- (void)setDefaultAddress: (UIButton *)sender
{
    NSInteger index = sender.tag - 1000;
    EMAddressInfo *addressInfo = [[EMAddressInfo alloc] initWithAddressInfo:_addressArray[index]];
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMSetAndDeleteAddressReqBody *reqBody = [[EMSetAndDeleteAddressReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"SET-DEFAULT-ADDRESS";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.ADDRESSID = addressInfo.m_id;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMSetAndDeleteAddressRespBody *respBody = [EMSetAndDeleteAddressRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            [app showTip:respBody.SUCCESSFULINFO];
            [self getUserAddress];
            [messageTable reloadData];
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];

}

- (void)deleteAddress: (UIButton *)sender
{
    NSInteger index = sender.tag - 1500;
    EMAddressInfo *addressInfo = [[EMAddressInfo alloc] initWithAddressInfo:_addressArray[index]];
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMSetAndDeleteAddressReqBody *reqBody = [[EMSetAndDeleteAddressReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"DELETE-USER-ADDRESS";
    reqBody.USERID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.ADDRESSID = addressInfo.m_id;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMSetAndDeleteAddressRespBody *respBody = [EMSetAndDeleteAddressRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            [app showTip:respBody.SUCCESSFULINFO];
            [self getUserAddress];
            [messageTable reloadData];
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
}

@end
